package com.林子祺.全名健康管理系统.view.servlet.login;

import com.林子祺.全名健康管理系统.dao.loginandregister.AccountComfirm;
import com.林子祺.全名健康管理系统.util.UserName;

import javax.servlet.*;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

//登录操作
@WebServlet("/login")
public class Login extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        req.setCharacterEncoding("utf-8");

        String username = req.getParameter("useremail");
        String password = req.getParameter("password");
        String CheckCode = req.getParameter("checkCode");

        HttpSession session = req.getSession();
        String check = (String) session.getAttribute("checkCode_session");

        if(check!= null && check.equalsIgnoreCase(CheckCode)){
            //忽略大小写比较
            //验证码正确
            //判断用户名和密码是否一致
            if(AccountComfirm.checkAccount(username,password)){//需要调用UserDao查询数据库
                //登录成功
                //存储信息，用户信息
                session.setAttribute("user",username);
                session.setAttribute("username", UserName.user);
                session.setAttribute("work",UserName.work);
                System.out.println(UserName.work);
                if(UserName.work.equals("3")) {
                    resp.sendRedirect(req.getContextPath() + "/login/admin.jsp");
                }
                else {
                    //重定向到success.jsp
                   resp.sendRedirect(req.getContextPath() + "/index.jsp");
                }
                UserName.user = null;
                UserName.work = "0";
            }
            else{
                //登录失败
                //存储提示信息到request
                req.setAttribute("login_error","用户名或密码错误");
                //转发到登录页面
                req.getRequestDispatcher("/login/login.jsp").forward(req,resp);
            }


        }else{
            //验证码不一致
            //存储提示信息到request
            req.setAttribute("cc_error","验证码错误");
            //转发到登录页面
            req.getRequestDispatcher("/login/login.jsp").forward(req,resp);

        }
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        this.doGet(req,resp);
    }
}
